package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.github.pagehelper.Page;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Value("${sky.shop.location}")
    private String shopLocation;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //判断订单是否距离是否正常
        String goalLocation = addressMapper.select(AddressBook.builder().id(ordersSubmitDTO.getAddressBookId()).build()).get(0).getDetail();
        Integer distance = BaiduMapUtil.getDistance(BaiduMapUtil.getLocation(shopLocation, ak), BaiduMapUtil.getLocation(goalLocation, ak), ak);
        log.info("配送距离{}m", distance);
        if(distance > 5000){
            throw new OrderBusinessException("超出配送范围");
        }

        //处理各种业务异常（地址簿为空，购物车数据为空）
        AddressBook getAddressBook = AddressBook.builder().id(ordersSubmitDTO.getAddressBookId()).build();
        AddressBook addressBook = addressMapper.select(getAddressBook).get(0);
        ShoppingCart getshoppingCart = ShoppingCart.builder().userId(BaseContext.getCurrentId()).build();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.select(getshoppingCart);
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()) + BaseContext.getCurrentId());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orderMapper.save(orders);
        redisTemplate.opsForValue().set("order:" + orders.getNumber(), 1, Duration.ofMinutes(15));
        //向订单明细插入n条数据
        for (ShoppingCart shoppingCart1 : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.save(orderDetail);
        }

        //清空当前购物车数据
        shoppingCartMapper.deleteAll(BaseContext.getCurrentId());

        //返回当前订单所需内容
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        log.info("提交订单信息返回：{}", ordersSubmitDTO);
        return orderSubmitVO;
    }

//    /**
//     * 订单支付，需要商铺号
//     *
//     * @param ordersPaymentDTO
//     * @return
//     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getByUserId(userId.toString());
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
//    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByUserId(userId.toString());

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        Integer flag = (Integer) redisTemplate.opsForValue().get("order:" + ordersPaymentDTO.getOrderNumber());
        if (flag == null) {
            throw new OrderBusinessException("订单已超时");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        // 替代微信支付成功后的数据库订单状态更新，直接在这里更新了
        // 根据订单号查询当前用户的该订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(1);
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED) // 订单状态，待接单
//                .payStatus(Orders.PAID) // 支付状态，已支付
//                .checkoutTime(LocalDateTime.now()) // 更新支付时间
//                .build();

        orderMapper.update(orders);
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "您有一个订单:" + ordersDB.getNumber() + " 已支付");
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return vo;
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = OrdersPageQueryDTO.builder()
                .page(page)
                .pageSize(pageSize)
                .status(status)
                .userId(BaseContext.getCurrentId())
                .build();

        Page<Orders> pageInfo = orderMapper.historyOrders(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (pageInfo != null) {
            for (Orders orders : pageInfo) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
                OrderVO orderVO = new OrderVO();
                orderVO.setOrderDetailList(orderDetailList);
                BeanUtils.copyProperties(orders, orderVO);
                list.add(orderVO);
            }
        }
        return new PageResult(pageInfo.getTotal(), list);
    }

    @Override
    public OrderVO getOrderDetail(Long id) {
        Orders orders = orderMapper.getByOrderId(id);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        orderVO.setOrderDetailList(orderDetailList);
        BeanUtils.copyProperties(orders, orderVO);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        log.info("用户{}取消订单，订单id为：{}", BaseContext.getCurrentId(), id);
        Orders orangeOrders = orderMapper.getByOrderId(id);
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .cancelReason("用户取消")
                .build();
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orangeOrders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单处于待接单状态下取消，需要进行退款
        if (orangeOrders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
//
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.update(orders);

    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        log.info("保存菜品");
        Orders orders = orderMapper.getByOrderId(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = ShoppingCart.builder()
                    .createTime(LocalDateTime.now())
                    .userId(BaseContext.getCurrentId())
                    .build();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCartMapper.save(shoppingCart);
        }
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 条件搜索订单
     * param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        log.info("获取订单信息");
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> pageInfo = orderMapper.historyOrders(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        if (pageInfo != null) {
            for (Orders orders : pageInfo) {
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
                String orderDishes = "";
                for (OrderDetail orderDetail : orderDetailList){
                    orderDishes = orderDishes + orderDetail.getName() + "*" + orderDetail.getNumber() + " ";
                }
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);
            }
        }
        return new PageResult(pageInfo.getTotal(), list);
    }

    /**
     * 订单统计
     * @return
     */
    @Override
    public OrderStatisticsVO orderStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(orderMapper.count(Orders.builder().status(Orders.TO_BE_CONFIRMED).build()));
        orderStatisticsVO.setConfirmed(orderMapper.count(Orders.builder().status(Orders.CONFIRMED).build()));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.count(Orders.builder().status(Orders.DELIVERY_IN_PROGRESS).build()));
        log.info("实时订单数量统计{}", orderStatisticsVO);
        return orderStatisticsVO;
    }

    /**
     * 修改订单状态
     * @param orders
     * @param status
     */
    @Override
    public void updateOrder(Orders orders, Integer status) {
        orders.setStatus(status);
        Integer preStatus = orderMapper.getByOrderId(orders.getId()).getStatus();
        //若为取消订单，则需要记录订单取消时间
        if (status.equals(Orders.CANCELLED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    orders.getNumber(), //商户订单号
//                    orders.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
            //当订单取消或者拒绝后，状态为2，3，4，5的订单需要退款
            if(preStatus >= 2){
                orders.setPayStatus(Orders.REFUND);
            }
            orders.setCancelTime(LocalDateTime.now());
            if(orders.getRejectionReason() != null){
                orders.setCancelReason(orders.getRejectionReason());
            }
        }
        if(status.equals(Orders.COMPLETED)){
            orders.setDeliveryTime(LocalDateTime.now());
        }
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        log.info("用户{}催单提醒", id);
        Orders orders = orderMapper.getByOrderId(id);
        if (!orders.getStatus().equals(Orders.REFUND)){
            throw new OrderBusinessException("订单已接受");
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号:" + orders.getNumber() + " 用户:" + orders.getUserId() + " 催单啦");
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
